package com.region.loadbalancer.http;

import com.region.loadbalancer.LoadBalancerConfig;
import com.region.loadbalancer.LoadBalancerManager;
import com.region.loadbalancer.http.apache.ApacheHttpClientInterceptor;
import com.region.loadbalancer.http.ok3.OkHttp3ClientInterceptor;
import com.region.plugin.InterceptorProxyManager;
import com.region.plugin.proxy.jdk.JdkProxyHandler;
import okhttp3.Call;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;

public class LoadBalancerHttpClientProxy {

    private static LoadBalancerHttpClientProxy INSTANCE = new LoadBalancerHttpClientProxy();

    public static LoadBalancerHttpClientProxy getInstance() {
        return INSTANCE;
    }

    private LoadBalancerManager loadBalancerManager = LoadBalancerManager.getInstance();

    public void setLoadBalancerConfig(LoadBalancerConfig loadBalancerConfig) {
        this.loadBalancerManager.setLoadBalancerConfig(loadBalancerConfig);
    }

    /**
     * Parsing link information and adding to service groups
     *
     * @param serverInfo
     * @return
     */
    public String addServersWithNoGroupName(String... serverInfo) {
        this.loadBalancerManager.initialization();
        return this.loadBalancerManager.addSocketInfoWithNoGroupName(serverInfo);
    }

    /**
     * Parsing link information and adding to service groups with no group name
     *
     * @param groupName
     * @param serverInfo
     * @return
     */
    public void addServers(String groupName, String... serverInfo) {
        this.loadBalancerManager.initialization();
        this.loadBalancerManager.addSocketInfo(groupName, serverInfo);
    }

    /**
     * Create Apache Http Client Proxy
     *
     * @param httpClient
     * @return
     */
    public HttpClient createApacheProxy(CloseableHttpClient httpClient) {
        InterceptorProxyManager proxyManager = InterceptorProxyManager.getNewInstance();
        proxyManager.setProxyTarget(JdkProxyHandler.class);
        proxyManager.addInterceptor(new ApacheHttpClientInterceptor(this.loadBalancerManager));
        return (HttpClient) proxyManager.doInterceptor(httpClient);
    }

    /**
     * Create Ok Http 3 Client Call Proxy
     *
     * @param call
     * @return
     */
    public Call createOkHttpProxy(Call call) {
        InterceptorProxyManager proxyManager = InterceptorProxyManager.getNewInstance();
        proxyManager.setProxyTarget(JdkProxyHandler.class);
        proxyManager.addInterceptor(new OkHttp3ClientInterceptor(this.loadBalancerManager));
        return (Call) proxyManager.doInterceptor(call);
    }

}